package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.SpliceAdapter;
import flc.ast.databinding.ActivityVideoSpliceBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoSpliceActivity extends BaseAc<ActivityVideoSpliceBinding> {

    public static List<String> listPath = new ArrayList<>();
    private long videoLength;
    private int playNum = 0;
    private String savePath = "";
    private SpliceAdapter splitAdapter;
    private int selPosition = 0;
    private Handler mHandler;

    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoLeftText.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_splice;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoSpliceBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivVideoSpliceSave.setOnClickListener(this);
        mDataBinding.ivVideoSpliceExperience.setOnClickListener(this);
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivVideoSpliceAdd.setOnClickListener(this);

        mDataBinding.rvVideoSpliceList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        splitAdapter = new SpliceAdapter();
        mDataBinding.rvVideoSpliceList.setAdapter(splitAdapter);
        splitAdapter.addChildClickViewIds(R.id.ivSpliceItemImg, R.id.ivSpliceItemExchange, R.id.ivSpliceItemDelete);
        splitAdapter.setOnItemClickListener(this);
        splitAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivVideoSpliceAdd://添加
                Intent intent = new Intent(this, SelVideoActivity.class);
                intent.putExtra(Content.Again, "Again");
                startActivityForResult(intent, Content.SPLIT_ADD);
                break;
            case R.id.ivVideoSpliceExperience://立即体验
                if (listPath.size() < 2) {
                    ToastUtils.showShort(getString(R.string.please_sel_two_video));
                    return;
                }
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                splitVideo();
                break;
            case R.id.ivVideoSpliceSave://保存
                if (TextUtils.isEmpty(savePath)) {
                    ToastUtils.showShort(R.string.please_video_splice);
                    return;
                }
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                saveVideo();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivSpliceItemImg://更换视频
                selPosition = position;
                Intent intent = new Intent(this, SelVideoActivity.class);
                intent.putExtra(Content.Again, "Again");
                startActivityForResult(intent, Content.SPLIT_REPLACE);
                break;
            case R.id.ivSpliceItemExchange://交换视频
                if (position == 0) return;
                Collections.swap(listPath, position - 1, position);
                updateData();
                setPlayer();
                break;
            case R.id.ivSpliceItemDelete://删除视频
                if (listPath.size() <= 1) {
                    ToastUtils.showShort(getString(R.string.just_have_one));
                    return;
                }
                listPath.remove(position);
                updateData();
                setPlayer();
                break;
        }
    }

    @Override
    protected void initData() {
        if (listPath.size() == 0) return;
        updateData();
        //设置播放器
        setPlayer();
    }

    //更新集合
    private void updateData() {
        splitAdapter.setList(listPath);
        splitAdapter.setPos(listPath.size() - 1);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        playNum = 0;
        splitAdapter.setCurrent(playNum);
        splitAdapter.notifyDataSetChanged();
        videoLength = MediaUtil.getDuration(listPath.get(0));
        mDataBinding.tvVideoLeftText.setText("00:00");
        mDataBinding.tvVideoRightText.setText("/" + TimeUtil.getMmss(videoLength));
        //设置播放器
        mDataBinding.videoView.setVideoPath(listPath.get(0));
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                playNum++;
                if (playNum < listPath.size()) {//继续播放下一个视频
                    splitAdapter.setCurrent(playNum);
                    splitAdapter.notifyDataSetChanged();
                    videoLength = MediaUtil.getDuration(listPath.get(playNum));
                    mDataBinding.tvVideoLeftText.setText("00:00");
                    mDataBinding.tvVideoRightText.setText("/" + TimeUtil.getMmss(videoLength));
                    videoLength = MediaUtil.getDuration(listPath.get(playNum));
                    mDataBinding.videoView.setVideoPath(listPath.get(playNum));
                    mDataBinding.videoView.seekTo(1);
                    mDataBinding.videoView.start();
                } else {//重新播放
                    setPlayer();
                }
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    //拼接视频
    private void splitVideo() {
        EditorHolder.editor().videoMerge(listPath, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.split_suc));
                savePath = outFilePath;
                mDataBinding.videoView.setVideoPath(outFilePath);
                mDataBinding.videoView.seekTo(1);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                mDataBinding.videoView.start();
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(R.string.split_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.split_ing) + progress + "%");
            }
        });
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, savePath);
                        String filePath = FileUtil.generateFilePath(Content.myRecord, "." + FileUtils.getFileExtension(savePath));
                        FileUtils.copy(savePath, filePath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String path = data.getStringExtra(Content.videoPath);
            if (requestCode == Content.SPLIT_REPLACE) {
                listPath.set(selPosition, path);
            } else if (requestCode == Content.SPLIT_ADD) {
                listPath.add(0, path);
            }
            updateData();
            setPlayer();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
        mDataBinding.videoView.pause();
        stopTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

}